import React, { useState, useCallback, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Button, 
  Select, 
  Space, 
  Typography, 
  Divider,
  message,
  Tooltip,
  Switch,
  Dropdown,
  Badge
} from 'antd';
import { 
  SaveOutlined, 
  ClearOutlined,
  InfoCircleOutlined,
  ExperimentOutlined,
  BugOutlined,
  DatabaseOutlined,
  ThunderboltOutlined,
  BookOutlined,
  FormatPainterOutlined,
  ArrowRightOutlined
} from '@ant-design/icons';
import { debounce } from 'lodash';
import SqlEditor, { createEditorMarker } from '../../components/SqlEditor/SqlEditor';
import UnifiedAnalysisPanel from '../../components/UnifiedAnalysisPanel/UnifiedAnalysisPanel';
import { 
  CompatibilityIssue,
  EditorMarker,
  DatabaseType,
  SqlExample,
  AnalysisConfig,
  UnifiedAnalysisResult
} from '../../types/analysis';
import { 
  analyzeSql,
  getSupportedDatabases, 
  getSqlExamples,
  formatSql,
  saveAnalysisTask,
  ManualSqlAnalysisRequest,
  ManualSqlAnalysisResponse 
} from '../../services/api';
import './ManualSqlAnalysis.css';

const { Title, Text } = Typography;
const { Option } = Select;

const ManualSqlAnalysis: React.FC = () => {
  // 基本状态
  const [sqlContent, setSqlContent] = useState<string>('');
  const [sourceDbType, setSourceDbType] = useState<string>('ORACLE');
  const [targetDbType, setTargetDbType] = useState<string>('GOLDENDB');
  const [analysisEngine, setAnalysisEngine] = useState<string>('RULE_BASED'); // 新增：分析引擎选择
  const [currentCursorPosition, setCurrentCursorPosition] = useState({ line: 1, column: 1 });
  
  // 分析相关状态
  const [analysisResult, setAnalysisResult] = useState<ManualSqlAnalysisResponse | null>(null);
  const [editorMarkers, setEditorMarkers] = useState<EditorMarker[]>([]);
  
  // 配置状态
  const [analysisConfig, setAnalysisConfig] = useState<AnalysisConfig>({
    enableRealTimeAnalysis: true,
    enableAutoOptimization: false,
    debounceDelay: 1500,
    maxResults: 100,
    showLineNumbers: true,
    highlightIssues: true
  });
  
  // 数据状态
  const [supportedDatabases, setSupportedDatabases] = useState<DatabaseType[]>([]);
  const [sqlExamples, setSqlExamples] = useState<SqlExample[]>([]);
  
  // 模拟用户ID
  const userId = 1;

  // 获取分析引擎提示信息
  const getAnalysisEngineTooltip = () => {
    switch (analysisEngine) {
      case 'RULE_BASED':
        return '基于预定义规则进行快速准确的兼容性检查';
      case 'LLM_BASED':
        return '使用AI大模型进行智能分析和优化建议';
      case 'HYBRID':
        return '结合规则引擎和AI引擎的混合分析模式';
      default:
        return '选择合适的分析引擎进行SQL兼容性检查';
    }
  };

  // 加载支持的数据库类型
  const loadSupportedDatabases = useCallback(async () => {
    try {
      const response = await getSupportedDatabases();
      if (response.success) {
        setSupportedDatabases(response.data);
      }
    } catch (error) {
      console.error('加载数据库类型失败:', error);
      // 使用默认数据库类型：Oracle、MySQL作为源数据库，GoldenDB作为目标数据库
      setSupportedDatabases([
        { value: 'ORACLE', label: 'Oracle' },
        { value: 'MYSQL', label: 'MySQL' },
        { value: 'GOLDENDB', label: 'GoldenDB' }
      ]);
    }
  }, []);

  // 加载SQL示例
  const loadSqlExamples = useCallback(async () => {
    try {
      const response = await getSqlExamples(undefined, sourceDbType);
      if (response.success) {
        setSqlExamples(response.data);
      }
    } catch (error) {
      console.error('加载SQL示例失败:', error);
      // 使用默认示例
      setSqlExamples([
        {
          id: 'oracle-basic',
          name: 'Oracle基础查询',
          description: '包含Oracle特有函数的基础查询',
          category: 'BASIC',
          difficulty: 'BASIC',
          sourceDbType: 'ORACLE',
          content: `-- Oracle示例SQL
SELECT 
    u.user_id,
    u.username,
    NVL2(u.email, u.email, 'N/A') as email_display,
    ROWNUM as row_num
FROM users u 
WHERE ROWNUM <= 10
ORDER BY u.created_date NULLS LAST;`,
          expectedIssues: 3
        },
        {
          id: 'mysql-basic',
          name: 'MySQL基础查询',
          description: '包含MySQL特有函数的基础查询',
          category: 'BASIC',
          difficulty: 'BASIC',
          sourceDbType: 'MYSQL',
          content: `-- MySQL示例SQL
SELECT 
    u.user_id,
    u.username,
    JSON_EXTRACT(u.profile, '$.email') as email,
    u.created_date
FROM users u 
WHERE u.status = 'active'
ORDER BY u.created_date DESC
LIMIT 10;`,
          expectedIssues: 2
        }
      ]);
    }
  }, [sourceDbType]);

  // 加载支持的数据库类型
  useEffect(() => {
    loadSupportedDatabases();
  }, [loadSupportedDatabases]);

  // 加载SQL示例
  useEffect(() => {
    loadSqlExamples();
  }, [loadSqlExamples]);

  // 实时分析处理函数
  const handleRealTimeAnalysis = useCallback(async (content: string) => {
    if (content.trim() && analysisConfig.enableRealTimeAnalysis) {
      // 暂时禁用实时分析以避免循环依赖
      console.log('Real-time analysis triggered for content:', content.substring(0, 50));
    }
  }, [analysisConfig.enableRealTimeAnalysis]);

  // 实时分析
  const debouncedAnalyze = useCallback(
    debounce(handleRealTimeAnalysis, analysisConfig.debounceDelay),
    [handleRealTimeAnalysis, analysisConfig.debounceDelay]
  );

  useEffect(() => {
    if (sqlContent.trim() && analysisConfig.enableRealTimeAnalysis) {
      debouncedAnalyze(sqlContent);
    }
  }, [sqlContent, debouncedAnalyze, analysisConfig.enableRealTimeAnalysis]);

  // 执行统一分析
  const performAnalysis = async (
    content: string = sqlContent, 
    useAiEnhancement: boolean = analysisEngine !== 'RULE_BASED',
    showMessage: boolean = true
  ): Promise<UnifiedAnalysisResult | null> => {
    if (!content.trim()) {
      if (showMessage) message.warning('请输入SQL语句');
      return null;
    }

    try {
      const request: ManualSqlAnalysisRequest = {
        sqlContent: content,
        sourceDbType,
        targetDbType,
        analysisEngine,
        enableLLMAnalysis: analysisEngine !== 'RULE_BASED',
        enableRuleOptimization: analysisEngine !== 'LLM_BASED'
      };

      const result = await analyzeSql(request);
      
      if (result.success) {
        setAnalysisResult(result.data);
        
        // 创建编辑器标记
        const markers = result.data.issues.map(issue => 
          createEditorMarker(issue)
        );
        setEditorMarkers(markers);
        
        if (showMessage) {
          const issueCount = result.data.totalIssues;
          if (issueCount === 0) {
            message.success('分析完成，未发现兼容性问题');
          } else {
            message.success(`分析完成，发现 ${issueCount} 个兼容性问题`);
          }
        }
        
        // 转换为UnifiedAnalysisResult格式
        const unifiedResult: UnifiedAnalysisResult = {
          success: true,
          sqlStatements: result.data.sqlStatements.map((stmt, index) => ({
            ...stmt,
            statementNumber: index + 1,
            lineNumber: stmt.lineNumber || 1
          })),
          issues: result.data.issues.map(issue => ({
            ...issue,
            analysisSource: 'RULE' as any,
            confidence: 0.95,
            statementNumber: 1,
            category: 'COMPATIBILITY' as any
          })),
          statistics: {
            totalStatements: result.data.sqlStatements?.length || 1,
            totalIssues: result.data.totalIssues,
            highSeverityCount: result.data.highSeverityCount,
            mediumSeverityCount: result.data.mediumSeverityCount,
            lowSeverityCount: result.data.lowSeverityCount,
            infoCount: 0,
            categoryCounts: {
              COMPATIBILITY: result.data.totalIssues,
              SYNTAX: 0,
              FUNCTION: 0,
              DATATYPE: 0,
              PERFORMANCE: 0,
              SECURITY: 0
            } as any,
            analysisTime: result.data.analysisTime ? result.data.analysisTime.toString() : new Date().toISOString(),
            processingTimeMs: 0
          },
          optimizations: []
        };
        
        return unifiedResult;
      } else {
        setAnalysisResult(null);
        setEditorMarkers([]);
        if (showMessage) {
          message.error(result.message || '分析失败');
        }
        return null;
      }
    } catch (error: any) {
      console.error('分析失败:', error);
      if (showMessage) {
        message.error(error.message || '分析失败，请检查网络连接');
      }
      setAnalysisResult(null);
      setEditorMarkers([]);
      return null;
    } finally {
      // Removed setIsAnalyzing(false) since isAnalyzing state was removed
    }
  };

  // 处理分析请求（来自UnifiedAnalysisPanel）
  const handleAnalysisRequest = useCallback(async (): Promise<UnifiedAnalysisResult> => {
    try {
      const request: ManualSqlAnalysisRequest = {
        sqlContent,
        sourceDbType,
        targetDbType,
        analysisEngine,
        enableLLMAnalysis: analysisEngine !== 'RULE_BASED',
        enableRuleOptimization: analysisEngine !== 'LLM_BASED'
      };

      const response = await analyzeSql(request);
      if (response.success) {
        const markers = response.data.issues.map(issue => createEditorMarker(issue));
        setEditorMarkers(markers);
        
        // 转换ManualSqlAnalysisResponse为UnifiedAnalysisResult格式
        const unifiedResult: UnifiedAnalysisResult = {
          success: true,
          sqlStatements: response.data.sqlStatements.map((stmt, index) => ({
            ...stmt,
            statementNumber: index + 1,
            lineNumber: stmt.lineNumber || 1
          })),
          issues: response.data.issues.map(issue => ({
            ...issue,
            analysisSource: 'RULE' as any,
            confidence: 0.95,
            statementNumber: 1,
            category: 'COMPATIBILITY' as any
          })),
          statistics: {
            totalStatements: response.data.sqlStatements?.length || 1,
            totalIssues: response.data.totalIssues,
            highSeverityCount: response.data.highSeverityCount,
            mediumSeverityCount: response.data.mediumSeverityCount,
            lowSeverityCount: response.data.lowSeverityCount,
            infoCount: 0,
            categoryCounts: {
              COMPATIBILITY: response.data.totalIssues,
              SYNTAX: 0,
              FUNCTION: 0,
              DATATYPE: 0,
              PERFORMANCE: 0,
              SECURITY: 0
            } as any,
            analysisTime: response.data.analysisTime ? response.data.analysisTime.toString() : new Date().toISOString(),
            processingTimeMs: 0
          },
          optimizations: []
        };
        
        return unifiedResult;
      } else {
        throw new Error(response.message || '分析失败');
      }
    } finally {
      // Removed setIsAnalyzing(false) since isAnalyzing state was removed
    }
  }, [sqlContent, sourceDbType, targetDbType, analysisEngine]);

  // 处理问题点击
  const handleIssueClick = useCallback((issue: CompatibilityIssue) => {
    // 跳转到编辑器对应位置
    setCurrentCursorPosition({ line: issue.lineNumber, column: issue.columnNumber });
    
    // 高亮显示问题
    message.info(`跳转到第 ${issue.lineNumber} 行：${issue.description}`);
  }, []);

  // 处理编辑器标记点击
  const handleMarkerClick = useCallback((marker: EditorMarker) => {
    if (marker.issueId && analysisResult) {
      const issue = analysisResult.issues.find(i => i.id === marker.issueId);
      if (issue) {
        handleIssueClick(issue);
      }
    }
  }, [analysisResult, handleIssueClick]);

  // 处理光标位置变化
  const handleCursorPositionChange = useCallback((line: number, column: number) => {
    setCurrentCursorPosition({ line, column });
  }, []);

  // 处理优化SQL应用
  const handleOptimizedSqlApply = useCallback((sql: string) => {
    setSqlContent(sql);
    message.success('已应用优化后的SQL');
  }, []);

  // 格式化SQL
  const handleFormatSql = async () => {
    if (!sqlContent.trim()) {
      message.warning('请输入SQL语句');
      return;
    }

    try {
      const response = await formatSql(sqlContent, sourceDbType);
      if (response.success) {
        setSqlContent(response.data.formattedSql);
        message.success('SQL格式化完成');
      } else {
        message.error(response.message || '格式化失败');
      }
    } catch (error: any) {
      console.error('格式化失败:', error);
      message.error(error.message || '格式化失败');
    }
  };

  // 加载示例SQL
  const handleLoadExample = (example: SqlExample) => {
    setSqlContent(example.content);
    setSourceDbType(example.sourceDbType);
    message.success(`已加载示例：${example.name}`);
  };

  // 保存分析任务
  const handleSaveTask = async () => {
    if (!analysisResult) {
      message.warning('请先执行SQL分析');
      return;
    }

    try {
      const response = await saveAnalysisTask({
        sqlContent,
        sourceDbType,
        targetDbType,
        taskName: `手动SQL分析_${new Date().toLocaleString()}`
      });

      if (response.success) {
        message.success('分析任务保存成功');
      } else {
        message.error(response.message || '保存失败');
      }
    } catch (error: any) {
      console.error('保存失败:', error);
      message.error(error.message || '保存失败');
    }
  };

  // 清空编辑器
  const handleClearEditor = () => {
    setSqlContent('');
    setAnalysisResult(null);
    setEditorMarkers([]);
  };

  // 渲染数据库选择器
  const renderDatabaseSelector = () => {
    // 源数据库选项：只包含 Oracle 和 MySQL
    const sourceDatabaseOptions = supportedDatabases.filter(db => 
      ['ORACLE', 'MYSQL'].includes(db.value)
    );
    
    // 目标数据库选项：只包含 GoldenDB
    const targetDatabaseOptions = supportedDatabases.filter(db => 
      db.value === 'GOLDENDB'
    );
    
    return (
      <Card size="small" className="database-selector-card">
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space>
              <Text strong>数据库迁移：</Text>
              <Select 
                value={sourceDbType} 
                onChange={setSourceDbType}
                style={{ width: 140 }}
                placeholder="源数据库"
                showSearch={false}
              >
                {sourceDatabaseOptions.map(db => (
                  <Option key={db.value} value={db.value}>
                    {db.label}
                  </Option>
                ))}
              </Select>
              
              <ArrowRightOutlined style={{ color: '#1890ff' }} />
              
              <Select 
                value={targetDbType} 
                onChange={setTargetDbType}
                style={{ width: 140 }}
                placeholder="目标数据库"
                showSearch={false}
              >
                {targetDatabaseOptions.map(db => (
                  <Option key={db.value} value={db.value}>
                    {db.label}
                  </Option>
                ))}
              </Select>
            </Space>
          </Col>
        
          {/* 分析引擎选择器 */}
          <Col>
            <Space>
              <Text strong>分析引擎：</Text>
              <Select 
                value={analysisEngine} 
                onChange={setAnalysisEngine}
                style={{ width: 160 }}
                placeholder="选择分析引擎"
                showSearch={false}
              >
                <Option value="RULE_BASED">
                  <Space>
                    <ThunderboltOutlined style={{ color: '#1890ff' }} />
                    规则引擎
                  </Space>
                </Option>
                <Option value="LLM_BASED">
                  <Space>
                    <ExperimentOutlined style={{ color: '#722ed1' }} />
                    AI引擎
                  </Space>
                </Option>
                <Option value="HYBRID">
                  <Space>
                    <BugOutlined style={{ color: '#fa8c16' }} />
                    混合模式
                  </Space>
                </Option>
              </Select>
              <Tooltip title={getAnalysisEngineTooltip()}>
                <InfoCircleOutlined style={{ color: '#999' }} />
              </Tooltip>
            </Space>
          </Col>
          
          <Col>
            <Space>
              {/* SQL示例下拉菜单 */}
              <Dropdown
                menu={{
                  items: sqlExamples.map(example => ({
                    key: example.id,
                    label: (
                      <Space>
                        <Badge 
                          count={example.expectedIssues || 0} 
                          size="small" 
                          color={(example.expectedIssues || 0) > 5 ? 'red' : (example.expectedIssues || 0) > 2 ? 'orange' : 'green'}
                        />
                        <div>
                          <div style={{ fontWeight: 500 }}>{example.name}</div>
                          <div style={{ fontSize: 12, color: '#666' }}>{example.description}</div>
                        </div>
                      </Space>
                    ),
                    onClick: () => handleLoadExample(example)
                  }))
                }}
                placement="bottomRight"
              >
                <Button icon={<BookOutlined />} size="small">
                  示例SQL
                </Button>
              </Dropdown>
              
              {/* 设置按钮 */}
              <Tooltip title="分析设置">
                <Switch
                  checked={analysisConfig.enableRealTimeAnalysis}
                  onChange={(checked) => setAnalysisConfig(prev => ({ ...prev, enableRealTimeAnalysis: checked }))}
                  checkedChildren="实时"
                  unCheckedChildren="手动"
                  size="small"
                />
              </Tooltip>
            </Space>
          </Col>
        </Row>
      </Card>
    );
  };

  // 渲染编辑器工具栏
  const renderEditorToolbar = () => (
    <Space style={{ marginBottom: 16 }}>
      <Button 
        icon={<FormatPainterOutlined />}
        onClick={handleFormatSql}
        size="small"
      >
        格式化
      </Button>
      <Button 
        icon={<SaveOutlined />}
        onClick={handleSaveTask}
        disabled={!analysisResult}
        size="small"
      >
        保存任务
      </Button>
      <Button 
        icon={<ClearOutlined />}
        onClick={handleClearEditor}
        size="small"
      >
        清空
      </Button>
      
      <Divider type="vertical" />
      
      <Text type="secondary" style={{ fontSize: 12 }}>
        行 {currentCursorPosition.line}, 列 {currentCursorPosition.column}
      </Text>
    </Space>
  );

  return (
    <div className="manual-sql-analysis">
      {/* 页面标题 */}
      <div className="analysis-header">
        <Title level={3}>
          <Space>
            <DatabaseOutlined />
            SQL兼容性分析
            <Badge dot color="green" />
          </Space>
        </Title>
        <Text type="secondary">
          支持规则引擎、AI引擎两种分析方式，实时检测SQL兼容性问题并提供优化建议
        </Text>
      </div>

      {/* 数据库选择器 */}
      {renderDatabaseSelector()}

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        {/* 左侧：SQL编辑器 */}
        <Col xs={24} lg={14}>
          <div className="editor-section">
            {renderEditorToolbar()}
            
            <SqlEditor
              value={sqlContent}
              onChange={setSqlContent}
              height={500}
              theme="vs-light"
              markers={editorMarkers}
              onMarkerClick={handleMarkerClick}
              onCursorPositionChange={handleCursorPositionChange}
              onFormat={handleFormatSql}
              showLineNumbers={analysisConfig.showLineNumbers}
              enableFormatting={true}
            />
          </div>
        </Col>

        {/* 右侧：分析面板 */}
        <Col xs={24} lg={10}>
          <UnifiedAnalysisPanel
            sqlContent={sqlContent}
            sourceDbType={sourceDbType}
            targetDbType={targetDbType}
            userId={userId}
            aiEnhancementEnabled={analysisEngine === 'LLM_BASED' || analysisEngine === 'HYBRID'}
            onAnalysisRequest={handleAnalysisRequest}
            onIssueClick={handleIssueClick}
            onOptimizedSqlApply={handleOptimizedSqlApply}
            config={analysisConfig}
          />
        </Col>
      </Row>
    </div>
  );
};

export default ManualSqlAnalysis;